package by.bsu.rfe.belianko.euniversity.controller.command;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.constants.ErrorMessages;
import by.bsu.rfe.belianko.euniversity.constants.LoggerMessages;
import by.bsu.rfe.belianko.euniversity.constants.PageNames;
import by.bsu.rfe.belianko.euniversity.dao.IAdmissionDAO;
import by.bsu.rfe.belianko.euniversity.exceptions.CommandException;
import by.bsu.rfe.belianko.euniversity.exceptions.DaoTechnicalException;
import by.bsu.rfe.belianko.euniversity.model.DataBaseLayer;

/**
 * Performs the registration of a user in the system.
 * 
 * @author Vitali_Belianko
 * 
 */
public class RegisterCommand implements Command {
	private static final String ADMISSION_STATE_OPEN = "Admission state: open";
	private static final String ADMISSION_STATE_COMPLETE = "Admission state: complete";
	private static final String COMPLETE = "complete";
	private static final String ERROR_MESSAGE = "errorMessage";
	private static final IAdmissionDAO admissionDao = DataBaseLayer.getIAdmissionDAO();
	private static final Logger LOGGER = Logger.getLogger(RegisterCommand.class);

	/**
	 * Check admission for complete and return the appropriate page.
	 * 
	 * @param request
	 * 
	 * @return login page if the admission is over, else register page
	 * @throws CommandException 
	 */
	@Override
	public String execute(HttpServletRequest request) throws CommandException {

		LOGGER.debug(LoggerMessages.STARTED_COMMAND);

		String admissionState = null;
		try {
			admissionState = admissionDao.getAdmissionState();
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(ErrorMessages.CAN_NOT_GET_ADMISSION_STATE, e);
		}

		if (COMPLETE.equals(admissionState)) {
			LOGGER.debug(ADMISSION_STATE_COMPLETE);
			request.setAttribute(ERROR_MESSAGE, ErrorMessages.ADMISSION_OVER);

			LOGGER.debug(LoggerMessages.FINISHED_COMMAND);

			return PageNames.LOGIN_PAGE;

		} else {

			LOGGER.debug(ADMISSION_STATE_OPEN);

			return PageNames.REGISTER_PAGE;
		}
	}

}
